<!-- 创建/编辑工单对话框 -->
<template>
  <el-dialog v-model="dialogVisible" :title="title" width="80%" style="max-width: 1200px" draggable @closed="handlerClosed">
    <el-form ref="formRef" style="width: 100%" :model="formData" :rules="formRules" label-width="90px">
      <el-form-item label="标题" prop="name">
        <el-input v-model="formData.name" style="width: 100%" placeholder="请输入标题" />
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <el-form-item label="类型" prop="woCategory">
            <el-select v-model="formData.woCategory" placeholder="请选择类型" style="width: 100%">
              <el-option v-for="item in woCategoryOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="woStatus">
            <el-radio-group v-model="formData.woStatus">
              <el-radio v-for="item in woStatusOptions" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="优先级" prop="woPriority">
            <el-radio-group v-model="formData.woPriority">
              <el-radio v-for="item in woPriorityOptions" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="描述">
        <Editor ref="editorRef" v-if="description" v-model="description" editorHeight="500px" />
      </el-form-item>
      <el-form-item label="图片" v-if="false">
        <!-- 使用原生 HTML input file -->
        <div class="file-upload-container">
          <input type="file" ref="fileInputRef" accept="image/*" @change="handleFileSelect" class="file-input" multiple />
          <div v-if="selectedFiles.length > 0" class="file-preview">
            <div v-for="(file, index) in selectedFiles" :key="index" class="preview-item">
              <img v-if="file.preview" :src="file.preview" class="preview-image" @click="previewImage(file.preview)" />
              <div class="file-info">
                <span class="file-name">{{ file.name }}</span>
                <el-button type="danger" icon="Delete" size="small" @click="removeFile(index)" circle />
              </div>
            </div>
          </div>
          <div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
            <el-progress :percentage="uploadProgress" />
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <div style="display: flex; justify-content: flex-end; width: 100%">
          <el-button type="primary" @click="submitForm(formRef)" :loading="isSubmitting"> 保存 </el-button>
          <el-button @click="resetForm(formRef)">重置</el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="图片预览" width="50%">
      <img :src="previewImageUrl" style="width: 100%" />
    </el-dialog>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { FormInstance } from 'element-plus'
import * as WorkOrder from '../../api/WorkOrder'
import { woCategoryOptions, woStatusOptions, woPriorityOptions } from './WorkOrderOptions'
import { useUsersStore } from '../../stores'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import storage from '../../utils/storage'
import Editor, { type EditorType } from '../../components/Editor.vue'
import _ from 'lodash'

// 文件相关引用
const fileInputRef = ref<HTMLInputElement | null>(null)
const selectedFiles = ref<{ file: File; name: string; preview: string }[]>([])
const uploadProgress = ref(0)
const isSubmitting = ref(false)
const previewVisible = ref(false)
const previewImageUrl = ref('')
const editorRef = ref<EditorType>()

const emits = defineEmits(['submited'])
const title = ref('新建工单')
const usersStore = useUsersStore()
// 表单引用
const formRef = ref<FormInstance>()

// 对话框是否显示
const dialogVisible = ref(false)
// 描述信息
const description = ref<string | undefined>(undefined)
// 表单数据
const formData = ref({
  id: null as number | null,
  name: null as string | null,
  woCategory: null as string | null,
  userId: null as number | null,
  userName: null as string | null,
  woStatus: 1,
  woPriority: null as string | null,
  woSolution: null as string | null,
  description: undefined as string | undefined, // 修改这一行
  imageUrls: [] as string[], // 用于保存上传图片的URL列表
})

// 表单验证规则
const formRules = ref({
  name: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  woCategory: [{ required: true, message: '请选择类型', trigger: 'change' }],
  woStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
  woPriority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
})

/**
 * 关闭对话框处理函数
 */
const handlerClosed = () => {
  dialogVisible.value = false
  // 清空文件选择
  selectedFiles.value = []
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }
  uploadProgress.value = 0
  resetForm(formRef.value)
}

/**
 * 打开对话框
 */
const open = async (val?: any) => {
  formData.value.woStatus = 1
  if (val) {
    title.value = '编辑工单'
    // console.log(val.id)
    const data = await WorkOrder.getById(val.id)
    // console.log('data', data)
    if (data.code === 200) {
      formData.value = data.data
      // formData.value.description = _.unescape(data.data.description)
      description.value = _.unescape(data.data.description)
      // 如果已有图片，初始化显示
      if (data.data.imageUrls && data.data.imageUrls.length > 0) {
        // 这里可以处理已有图片的显示，如果需要的话
      }
    }
  } else {
    resetForm(formRef.value)
    const { userId, username } = usersStore.getAllState()
    formData.value.userId = userId ?? null
    formData.value.userName = username ?? null
  }
  dialogVisible.value = true
}

/**
 * 处理文件选择
 */
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files

  if (files && files.length > 0) {
    for (let i = 0; i < files.length; i++) {
      const file = files[i]

      // 验证文件类型和大小
      if (!file.type.startsWith('image/')) {
        ElMessage.error('请选择图片文件!')
        continue
      }

      if (file.size > 5 * 1024 * 1024) {
        // 5MB
        ElMessage.error('文件大小不能超过5MB!')
        continue
      }

      // 创建预览URL
      const preview = URL.createObjectURL(file)

      selectedFiles.value.push({
        file: file,
        name: file.name,
        preview: preview,
      })
    }
  }
}

/**
 * 移除选中的文件
 */
const removeFile = (index: number) => {
  // 释放预览URL
  URL.revokeObjectURL(selectedFiles.value[index].preview)
  selectedFiles.value.splice(index, 1)
  ElMessage.success('文件已移除')
}

/**
 * 预览图片
 */
const previewImage = (url: string) => {
  previewImageUrl.value = url
  previewVisible.value = true
}

/**
 * 上传文件到服务器
 */
const uploadFiles = async (): Promise<string[]> => {
  if (selectedFiles.value.length === 0) {
    return []
  }

  const uploadedUrls: string[] = []

  for (let i = 0; i < selectedFiles.value.length; i++) {
    const fileItem = selectedFiles.value[i]
    const formData = new FormData()
    formData.append('file', fileItem.file)

    const token = storage.get('CURRENT_TOKEN', '')
    const config = {
      headers: {
        'Content-Type': 'multipart/form-data',
        Authorization: `Bearer ${token}`,
      },
    }
    try {
      // const response = await axios.post('/dev-api/oa/woorder/avatar', formData, config)
      const response = await axios.post(
        '/dev-api/oa/woorder/avatar',
        {
          avatarfile: fileItem.file,
        },
        config
      )
      console.log('response', response)
      // const response = await fetch('/dev-api/oa/woorder/avatar', {
      //   method: 'POST',
      //   body: formData,
      // })

      // if (response.ok) {
      //   const result = await response.json()
      //   // 假设后端返回格式为 { code: 200, data: { url: '图片URL' } }
      //   if (result.code === 200 && result.data?.url) {
      //     uploadedUrls.push(result.data.url)
      //   } else {
      //     throw new Error(result.msg || '上传失败')
      //   }
      // } else {
      //   throw new Error('网络请求失败')
      // }
    } catch (error) {
      console.error('上传失败:', error)
      ElMessage.error(`文件 ${fileItem.name} 上传失败: ${error}`)
      throw error
    }
  }

  return uploadedUrls
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      isSubmitting.value = true
      try {
        // 上传文件
        const imageUrls = await uploadFiles()

        // 将上传的图片URL添加到表单数据中
        formData.value.imageUrls = imageUrls

        const params = formData.value
        // params.description
        params.description = _.escape(description.value)
        let data: any = null
        if (params.id) {
          data = await WorkOrder.put(params)
        } else {
          data = await WorkOrder.add(params)
        }

        if (data.code === 200) {
          ElMessage.success(data.msg)
          handlerClosed()
          emits('submited')
        } else {
          ElMessage.error(data.msg)
        }
      } catch (error) {
        ElMessage.error('提交失败，请重试')
        console.error('提交失败:', error)
      } finally {
        isSubmitting.value = false
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formData.value = {
    id: null,
    name: null,
    woCategory: null,
    userId: null,
    userName: null,
    woStatus: 1,
    woPriority: null,
    woSolution: null,
    description: undefined, // 修改这一行

    imageUrls: [],
  }
  description.value = ''
  formEl.resetFields()
  selectedFiles.value = []
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }
  uploadProgress.value = 0
}

defineExpose({ open })
</script>

<style lang="scss" scoped>
.file-upload-container {
  width: 100%;
}

.file-input {
  width: 100%;
  padding: 10px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.file-input:hover {
  border-color: #409eff;
}

.file-preview {
  margin-top: 10px;
}

.preview-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 5px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.preview-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

.file-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.file-name {
  font-size: 14px;
  color: #606266;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.upload-progress {
  margin-top: 10px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
